#include "mainwindow.h"
#include "build_config.h"

#include <DApplication>
#include <DBlurEffectWidget>
#include <DWidgetUtil>
#include <DApplicationSettings>
#include <DAboutDialog>

#include <QAction>

const QString &HomePageName = "gitee.com/ct243768648/ccc-proc-info-plugin";
const QString &HomePage = "https://gitee.com/ct243768648/ccc-proc-info-plugin";

DAboutDialog *AboutDialog;

DWIDGET_USE_NAMESPACE
DCORE_USE_NAMESPACE

void initAboutDlg()
{
    DApplication *dApp = qobject_cast<DApplication *>(qApp);
    AboutDialog = new DAboutDialog();
    AboutDialog->setProductName(dApp->productName());
    AboutDialog->setProductIcon(dApp->productIcon());
    AboutDialog->setVersion(dApp->translate("DAboutDialog", "%1").arg(dApp->applicationVersion()));
    AboutDialog->setDescription(dApp->applicationDescription());
    if (!dApp->applicationLicense().isEmpty()) {
        AboutDialog->setLicense(dApp->translate("DAboutDialog", "%1 is released under %2")
                                    .arg(dApp->productName()).arg(dApp->applicationLicense()));
    }
    AboutDialog->setWebsiteName(HomePageName);
    AboutDialog->setWebsiteLink(HomePage);

    dApp->setAboutDialog(AboutDialog);
}

void openAboutDlg()
{
    if (DGuiApplicationHelper::isTabletEnvironment()) {
        AboutDialog->exec();
    } else {
        AboutDialog->show();
    }
}

void actionByExecParam(MainWindow &w) {
    QFile f(ExecParamsCfgFilePath);
    if (!f.open(QIODevice::OpenModeFlag::ReadOnly)) {
        qCritical() << Q_FUNC_INFO << ExecParamsCfgFilePath << "open failed, launcher by default";
        return;
    }

    QByteArray content = f.readAll();
    f.close();
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(content, &err);
    if (err.error != QJsonParseError::NoError) {
        qCritical() << Q_FUNC_INFO << "parse json failed";
        return;
    }

    QJsonObject mainJsonObj = doc.object();
    // 根据参数执行
    for (;;) {
        // 是否打开设置界面
        bool openSettingsPage = false;
        if (mainJsonObj.keys().contains(EXEC_PARAMS_CFG_KEY_OPEN_SETTINGS_PAGE)) {
            openSettingsPage = mainJsonObj.value(EXEC_PARAMS_CFG_KEY_OPEN_SETTINGS_PAGE).toBool();
        }
        if (openSettingsPage) {
            w.openSettingsPage();
            break;
        }

        // 是否打开关于界面
        bool needOpenAboutDlg = false;
        if (mainJsonObj.keys().contains(EXEC_PARAMS_CFG_KEY_OPEN_ABOUT_DLG)) {
            needOpenAboutDlg = mainJsonObj.value(EXEC_PARAMS_CFG_KEY_OPEN_ABOUT_DLG).toBool();
        }
        if (needOpenAboutDlg) {
            openAboutDlg();
            break;
        }
        break;
    }

    // 执行参数只使用一次
    QFile::remove(ExecParamsCfgFilePath);
}

void writeExecParam(const QVariantMap &paramMap) {
    QFileInfo fInfo(ExecParamsCfgFilePath);
    if (!fInfo.dir().exists()) {
        fInfo.dir().mkdir(fInfo.dir().path());
    }

    QFile f(ExecParamsCfgFilePath);
    if (!f.open(QIODevice::OpenModeFlag::WriteOnly)) {
        qCritical() << Q_FUNC_INFO << ExecParamsCfgFilePath << "open failed";
        return;
    }

    QJsonObject mainJsonObj;
    for (QVariantMap::const_iterator iter = paramMap.constBegin(); iter != paramMap.constEnd(); ++iter) {
        mainJsonObj.insert(iter.key(), iter.value().toJsonValue());
    }
    QJsonDocument doc(mainJsonObj);

    f.write(doc.toJson());
    f.close();
}

int main(int argc, char *argv[])
{
    DApplication a(argc, argv);
    a.setAttribute(Qt::AA_UseHighDpiPixmaps); // 高清图
    a.setOrganizationName("ccc");
    a.setApplicationName("进程信息");
    a.setApplicationVersion(BUILD_VERSION);
    a.loadTranslator();
    a.setApplicationDisplayName(QObject::tr("Process Infomations Window"));
    a.setStyle("chameleon");
    a.setWindowIcon(QIcon::fromTheme("waterflow"));
    a.setProductIcon(QIcon::fromTheme("waterflow"));
    a.setApplicationDescription(QApplication::translate("main", "查看进程信息，包括网速、包名等"));
    a.setQuitOnLastWindowClosed(false);

    initAboutDlg();

    // 解析参数
    QCommandLineParser cmdLineParser;
    cmdLineParser.addVersionOption();
    cmdLineParser.addHelpOption();

    QCommandLineOption openSettingsPageOp(EXEC_PARAMS_CFG_KEY_OPEN_SETTINGS_PAGE);
    openSettingsPageOp.setDescription("打开设置界面");
    cmdLineParser.addOption(openSettingsPageOp);

    QCommandLineOption openAboutDlgOp(EXEC_PARAMS_CFG_KEY_OPEN_ABOUT_DLG);
    openSettingsPageOp.setDescription("打开关于");
    cmdLineParser.addOption(openAboutDlgOp);

    cmdLineParser.process(a);

    QVariantMap paramMap;
    if (cmdLineParser.isSet(openSettingsPageOp)) {
        paramMap.insert(EXEC_PARAMS_CFG_KEY_OPEN_SETTINGS_PAGE, true);
    }
    if (cmdLineParser.isSet(openAboutDlgOp)) {
        paramMap.insert(EXEC_PARAMS_CFG_KEY_OPEN_ABOUT_DLG, true);
    }

    if (!paramMap.isEmpty()) {
        writeExecParam(paramMap);
    }

    if (!a.setSingleInstance("ccc-proc-info-window")) {
        qInfo() << Q_FUNC_INFO << "单例程序，已存在一个进程";
        exit(0);
    }

    DApplicationSettings settings;

    MainWindow w;
    w.show();

    Dtk::Widget::moveToCenter(&w);

    QObject::connect(&a, &DApplication::newInstanceStarted, &a, [&w] {
        qInfo() << "newInstanceStarted";
        w.activateWindow();
        actionByExecParam(w);
    });

    actionByExecParam(w);
    a.exec();
}
